<template>
  <div id="user">
    <!-- 面包屑 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>用户管理</el-breadcrumb-item>
      <el-breadcrumb-item>用户列表</el-breadcrumb-item>
    </el-breadcrumb>
    <el-card class="box-card">
      <el-row :gutter="15">
        <el-col :span="7">
          <el-input placeholder="请输入内容" v-model="queryInfo.query" clearable @clear="getUserList">
            <el-button slot="append" icon="el-icon-search" @click="getUserList"></el-button>
          </el-input>
        </el-col>
        <el-col :span="4">
          <el-button type="primary" @click="addDialogVisible=true">添加用户</el-button>
        </el-col>
      </el-row>
      <el-table :data="userlist" border stripe>
        <el-table-column label="#" type="index"></el-table-column>
        <el-table-column label="姓名" prop="username"></el-table-column>
        <el-table-column label="电话" prop="mobile"></el-table-column>
        <el-table-column label="邮箱" prop="email"></el-table-column>
        <el-table-column label="角色" prop="role_name"></el-table-column>
        <el-table-column label="状态">
          <template slot-scope="scope">
            <el-switch v-model="scope.row.mg_state" @change="chageUserState(scope.row)">
            </el-switch>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="181" fixed="right">
          <template slot-scope="scope">
            <el-button type="primary" icon="el-icon-edit" size="mini" @click="showEditDialog(scope.row.id)"></el-button>
            <el-button type="danger" icon="el-icon-delete" size="mini" @click="removeUserById(scope.row.id)"></el-button>
            <!-- el-tooltip用于文字提示 -->
            <el-tooltip class="item" effect="dark" content="分配角色" placement="top" :enterable="false">
              <el-button type="warning" icon="el-icon-setting" size="mini" @click="setRole(scope.row)"></el-button>
            </el-tooltip>
          </template>
        </el-table-column>
      </el-table>
      <el-pagination @size-change="handleSizeChange" @current-change="handleCurrentChange"
        :current-page="queryInfo.pagenum" :page-sizes="[5, 10, 20, 30]" :page-size="queryInfo.pagesize"
        layout="total, sizes, prev, pager, next, jumper" :total="total">
      </el-pagination>
    </el-card>
    <!-- 添加用户 -->
    <el-dialog title="添加用户" :visible.sync="addDialogVisible" width="50%" @close="addDialogClosed">
      <el-form :model="addForm" :rules="addFormRules" ref="addFormRef" label-width="70px">
        <el-form-item label="用户名" prop="username">
          <el-input v-model="addForm.username"></el-input>
        </el-form-item>
        <el-form-item label="密码" prop="password">
          <el-input v-model="addForm.password" type="password"></el-input>
        </el-form-item>
        <el-form-item label="电话" prop="mobile">
          <el-input v-model="addForm.mobile"></el-input>
        </el-form-item>
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="addForm.email"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button type="primary" @click="addUser">确 定</el-button>
        <el-button @click="addDialogVisible = false">取 消</el-button>
      </span>
    </el-dialog>
    <!-- 编辑用户 -->
    <el-dialog title="编辑用户" :visible.sync="editDialogVisible" width="50%">
      <el-form :model="editForm" label-width="70px" :rules="editFormRules" ref="editFormRef">
        <el-form-item label="用户名">
          <el-input v-model="editForm.username" disabled></el-input>
        </el-form-item>
        <el-form-item label="电话" prop="mobile">
          <el-input v-model="editForm.mobile"></el-input>
        </el-form-item>
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="editForm.email"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button type="primary" @click="editUser()">确 定</el-button>
        <el-button @click="editDialogClosed">取 消</el-button>
      </span>
    </el-dialog>
    <!-- 分配角色 -->
    <el-dialog title="分配角色" :visible.sync="setRoleDialogVisible" width="50%" @close="setRoleDialogClosed">
      <el-form :model="userInfo" label-width="90px">
        <el-form-item label="用户名">
          <el-input v-model="userInfo.username" disabled></el-input>
        </el-form-item>
        <el-form-item label="当前角色">
          <el-input v-model="userInfo.role_name" disabled></el-input>
        </el-form-item>
        <el-form-item label="分配新角色" placeholder="请选择新角色">
          <el-select v-model="selectedRoleId">
            <el-option v-for="item in rolesList" :key="item.id" :label="item.roleName" :value="item.id"></el-option>
          </el-select>
        </el-form-item>
      </el-form>  
      <span slot="footer" class="dialog-footer">
          <el-button type="primary" @click="saveRoleInfo">确 定</el-button>
          <el-button @click="setRoleDialogVisible = false">取 消</el-button>
        </span>
    </el-dialog>
  </div>
</template>

<script>
export default {
    name: 'user',
    data(){
      // 自定义校验规则-手机
      var checkMobile = (rule,value,callback) => {
        const regMobile = /^[1][3,4,5,7,8][0-9]{9}$/
        if(regMobile.test(value)){
          return callback()
        }
        callback(new Error("请输入合法手机号！"))
      }
      // 自定义校验规则-邮箱
      var checkEmail = (rule,value,callback) => {
        // 验证邮箱是否合法的正则表达式
        const regEmail = /^[A-Za-z\d]+([-_.][A-Za-z\d]+)*@([A-Za-z\d]+[-.])+[A-Za-z\d]{2,4}$/
        if(regEmail.test(value)){
          // 校验通过
          return callback()
        }
        callback(new Error("请输入合法邮箱！"))
      }
      return{
        queryInfo:{
          query: '',
          pagenum: 1,
          pagesize: 5
        },
        userlist: [],
        total: 0,
        addDialogVisible:false,
        addForm:{
          username:'',
          password:'',
          mobile:'',
          email:'',
        },
        // 添加用户时的校验规则
        addFormRules:{
          username:[{required: true, message:'请输入用户名', trigger: 'blur'},
                    {min:3,max:10,message:"长度在3-10位间",trigger:'blur'}],
          password:[{required: true, message:'请输入密码', trigger: 'blur'},
                    {min:6,max:15,message:"长度在6-15位间",trigger:'blur'}],
          mobile:[{validator:checkMobile, trigger: 'blur'}],
          email:[{validator:checkEmail, trigger: 'blur'}],
        },
        editDialogVisible:false,
        editForm:{},
        editFormRules:{
          mobile:[{validator:checkMobile, trigger: 'blur'}],
          email:[{validator:checkEmail, trigger: 'blur'}],
        },
        // 控制分配角色对话框的显示与隐藏
        setRoleDialogVisible:false,
        // 需要被分配权限的用户信息
        userInfo:{},
        rolesList:[],
        // 已选中的角色id
        selectedRoleId:''
      }
    },
    created(){
      this.getUserList()
    },
    methods:{
      // 获取用户信息
      async getUserList(){
        this.$http.get('users',{params:this.queryInfo}).then(res =>{
          if(res.data.meta.status == 200){
            this.userlist = res.data.data.users
            this.total = res.data.data.total
          }else{
            this.$message({
              message: res.data.meta.msg,
              type: 'error',
              duration: 20000
            })
          }
        })
      },
      // 每页显示条数发送变化
      handleSizeChange(newSize){
        this.queryInfo.pagesize = newSize
        this.getUserList()
      },
      // 当前页发生变化
      handleCurrentChange(newPage){
        this.queryInfo.pagenum = newPage
        this.getUserList()
      },
      // 点击开关修改用户状态
      async chageUserState(userinfo){
        await this.$http.put(`users/${userinfo.id}/state/${userinfo.mg_state}`).then(res => {
          if(res.data.meta.status == 200){
            this.$message({
              message: res.data.meta.msg,
              type: 'success',
              duration: 1000
            })
          }else{
            // 操作失败时还原用户状态
            userinfo.mg_state = !userinfo.mg_state
            return this.$message({
              message: res.data.meta.msg,
              type: 'error',
              duration: 20000
            })
          }
        })
      },
      // 监听添加用户对话框关闭事件
      addDialogClosed(){
        this.$refs.addFormRef.resetFields()
      },
      // 添加用户
      async addUser(){
        await this.$refs.addFormRef.validate(valid => {
          if(valid){
            this.$http.post('users',this.addForm).then(res =>{
              if(res.data.meta.status == 201){
               this.$message({
                 message: res.data.meta.msg,
                 type: 'success',
                 duration: 600
               })
               this.addDialogVisible = false
               this.getUserList()
             }else{
               return this.$message({
                 message: res.data.meta.msg,
                 type: 'error',
                 duration: 2000
               })
             }
            })
          }
        })
      },
      // 显示编辑用户对话框
      async showEditDialog(id){
        await this.$http.get('users/'+id).then(res => {
          if(res.data.meta.status == 200){
            this.editForm = res.data.data
            this.editDialogVisible = true
          }else{
            return this.$message({
              message: res.data.meta.msg,
              type: 'error',
              duration: 2000
            })
          }
        })
      },
      // 监听添加用户对话框关闭事件
      editDialogClosed(){
        this.$refs.editFormRef.resetFields()
        this,this.editDialogVisible = false
      },
      // 编辑用户
      editUser(){
        this.$refs.editFormRef.validate(async (valid) => {
          if(!valid) return
          //发起修改用户信息的请求
          await this.$http.put("users/"+this.editForm.id,{email:this.editForm.email,mobile:this.editForm.mobile}).then(res => {
            if(res.data.meta.status == 200){
              this.editDialogVisible = false
              this.getUserList()
              this.$message({
                message: res.data.meta.msg,
                type: 'success',
                duration: 1000
              })
            }else{
              return this.$message({
                message: res.data.meta.msg,
                type: 'error',
                duration: 2000
              })
            }
          })
        })
      },
      //删除用户
      async removeUserById(id){
        await this.$confirm('确定删除该用户吗？', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          this.$http.delete("users/"+id).then(res => {
            if(res.data.meta.status == 200){
              this.getUserList()
              this.$message({
                type: 'success',
                message: '删除成功!'
              });
            }else{
              this.$message({
                type: 'error',
                message: res.data.meta.msg
              });
            }
          })
        }).catch( err => {
          return err
        });
      },
      // 显示分配角色对话框
      async setRole(userInfo){
        this.userInfo =userInfo
        // 获取所有角色列表
        await this.$http.get('roles').then(res => {
          if(res.data.meta.status == 200){
            this.rolesList = res.data.data
          }else{
            return this.$message({
              type: 'error',
              message: res.data.meta.msg
            });
          }
        })
        this.setRoleDialogVisible = true
      },
      // 分配角色
      async saveRoleInfo(){
        if(!this.selectedRoleId){
          return this.$message({
            type: 'error',
            message: '请选择要分配的角色！'
          });
        }
        await this.$http.put(`users/${this.userInfo.id}/role`,{rid:this.selectedRoleId}).then(res => {
          if(res.data.meta.status == 200){
            this.$message({
              type: 'success',
              message: res.data.meta.msg,
              duration:600
            });
            this.setRoleDialogVisible = false
            this.getUserList()
          }else{
            return this.$message({
              type: 'error',
              message: res.data.meta.msg,
              duration:2000
            });
          }
        })
      },
      // 监听分配角色对话框的关闭事件
      setRoleDialogClosed(){
        this.selectedRoleId=''
        this.userInfo={}
      }
    }
}
</script>

<style scoped>

</style>